<?php

namespace Icsoc\SoundBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * Class SoundController
 * @package Icsoc\SoundBundle\Controller
 */
class SoundController extends BaseController
{
    /**
     * @return Response
     */
    public function indexAction()
    {
        $soundType = $this->container->getParameter('sound_type');
        $types = $this->container->getParameter("sound_type");
        $types[0] = $this->trans("Please select the type of speech");
        ksort($types);
        return $this->render('IcsocSoundBundle:Sound:index.html.twig', array(
                'sound_type' => $soundType,
                'types' => $types
            ));
    }

    /**
     * 语音列表；
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');

        $info = array(
            'pagination'=>array('rows'=>$rows, 'page'=>$page),
            'filter'=> !empty($fliter) ? json_decode($fliter, true) : array(),
            'sort'=>array('order'=>$sord,'field'=>$sidx),
        );
        $vcc_code = $this->getUser()->getVccCode();
        $list = $this->container->get('icsoc_data.model.sound')
            ->soundList(array('vcc_code'=>$vcc_code, 'info'=>json_encode($info)));
        $data['rows'] = (isset($list['data']) && !empty($list['data'])) ? $list['data'] : array();
        $data['page'] = $page;
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;
        return new JsonResponse($data);
    }

    /**
     * 操作语音；
     * @param Request $request
     * @return JsonResponse
     */
    public function oprAction(Request $request)
    {
        $opr = trim($request->get('oper', ''));
        $vccCode = $this->getVccCode();
        if ($opr == 'del') {
            $ids = $request->get('id', '0');
            $soundId = explode(',', $ids);
            $arr = array('vcc_code'=>$vccCode,'sound_id'=>$soundId);
            $sounds = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinSounds")->getSoundNames($vccCode);
            $message = $this->get('icsoc_data.model.sound')->delSound($arr);
            if (isset($message['code']) && $message['code'] == 500) {
                $success = $error = array();
                foreach ($message['data'] as $val) {
                    if ($val['code'] == 200) {
                        $success[] = isset($sounds[$val['sound_id']]) ? $sounds[$val['sound_id']] : '';
                    } else {
                        $message = isset($sounds[$val['sound_id']]) ? $sounds[$val['sound_id']] : '';
                        $message.=$val['message'];
                        $error[] = $message;
                    }
                }
                $message = $this->trans('Delete fail').'['.implode(',', $error)."] <br/>";
                $message.= $this->trans('Delete success').'['.implode(',', $success).'] <br/>';
                return new JsonResponse(array('error'=>0, 'message'=>$message));
            } else {
                return new JsonResponse(array('error'=>1, 'message'=>$message['message']));
            }
        } else {
            return new JsonResponse(array('error'=>1,'message'=>''));
        }
    }

    /**
     * 添加语音
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            $request->query->set('vcc_code', $this->getUser()->getVccCode());
            $msg = $this->get('icsoc_data.model.sound')->upload($request);
            if (isset($msg['code']) && $msg['code'] == '200') {
                $data = array(
                    'data'=>array(
                        'msg_detail'=>$this->trans('Add voice success'),
                        'type' => 'success',
                        'link' => array(
                            array('text'=>$this->trans('Continue to add voice'),
                                'href'=>$this->generateUrl('icsoc_sound_add')),
                            array('text'=>$this->trans('Speech list'),'href'=>$this->generateUrl('icsoc_sound_index')),
                        )
                    )
                );
            } else {
                $data = array('data'=>array('msg_detail'=>$msg['message'],'type'=>'danger'));
            }
            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        $sountType = $this->container->getParameter('sound_type');
        return $this->render("IcsocSoundBundle:Sound:soundInfo.html.twig", array(
                'soundType' => $sountType
            ));
    }

    /**
     * 编辑
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request)
    {
        $arr['vcc_code'] = $this->getUser()->getVccCode();
        $arr['sound_id'] = $request->get('id', 0);
        if ($request->getMethod() == 'POST') {
            $request->query->set('vcc_code', $arr['vcc_code']);
            $msg = $this->get('icsoc_data.model.sound')->updateSound($request);
            if (isset($msg['code']) && $msg['code'] == '200') {
                $data = array(
                    'data'=>array(
                        'msg_detail'=>$this->trans("Successful modification"),
                        'type' => 'success',
                        'link' => array(
                            array(
                                'text'=>$this->trans('return'),
                                'href'=>$this->generateUrl('icsoc_sound_edit', array('sound_id'=>$arr['sound_id']))
                            ),
                            array('text'=>$this->trans('Speech list'),'href'=>$this->generateUrl('icsoc_sound_index')),
                        )
                    )
                );
            } else {
                $data = array('data'=>array('msg_detail'=>$msg['message'],'type'=>'danger'));
            }
            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        $info = $this->get('icsoc_data.model.sound')->getSoundInfo($arr);
        $sountType = $this->container->getParameter('sound_type');
        return $this->render("IcsocSoundBundle:Sound:editSound.html.twig", array(
                'soundType' => $sountType,
                'info' => $info,
            ));
    }

    /**
     * 播放语音
     * @param Request $request
     * @return Response
     */
    public function playAction(Request $request)
    {
        $soundId = $request->get('sound_id', '');
        $vccCode = $this->getVccCode();
        $info = $this->get('icsoc_data.model.sound')->getSoundInfo(array('vcc_code'=>$vccCode, 'sound_id'=>$soundId));
        $flysystem = $this->get("icsoc_filesystem");
        try {
            $content = $flysystem->read($info['address']);

            return new Response($content, 200, array(
                'Pragma' => 'Public',
                'Expires' => 0,
                'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                'Content-type' => 'audio/x-wav',
                'Content-Length' => strlen($content),
                'Content-Transfer-Encoding' => 'binary',
                'Accept-Ranges' => 'bytes',
                'Content-Disposition' => 'attachment;filename='.basename($info['address']),
            ));
        } catch (\Exception $e) {
            $this->get('logger')->error($e->getMessage());

            return new Response("语音不存在");
        }
    }
}
